package purchases

import (
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/cmsserver/orderplan"
	"oxy_server/until"
	"github.com/rs/xid"
	"time"
)

type (
	Purchases struct {
		ID          bson.ObjectId       `json:"_id" bson:"_id"`
		OrderNumber string              `json:"ordernumber" bson:"ordernumber"` //订单号
		ProductIds  []string            `json:"productids" bson:"productids"`   //产品id 数组
		Products    []orderplan.Product `json:"products" bson:"products"`       //产品列表
		MaterialIds  []string   		`json:"materialids" bson:"materialids"` //物料单ids
		Materials   []Material          `json:"materials" bson:"materials"`     //物料单信息汇总
		Creuser     string              `json:"createuser" bson:"createuser"`   //创建人
		Cretime     time.Time           `json:"createtime" bson:"createtime"`   //创建时间
		Upduser     string              `json:"updateuser" bson:"updateuser"`   //更新人
		Updtime     time.Time           `json:"updatetime" bson:"updatetime"`   //更新时间
	}
	InsertPurchases struct {
		OrderNumber string     `json:"ordernumber" bson:"ordernumber"` //订单号
		ProductIds  []string   `json:"productids" bson:"productids"`   //组
		MaterialIds  []string   `json:"materialids" bson:"materialids"` //物料单ids
		Materials   []Material `json:"materials" bson:"materials"`     //物料单信息汇总
		Creuser     string     `json:"createuser" bson:"createuser"`   //创建人
		Cretime     time.Time  `json:"createtime" bson:"createtime"`   //创建时间
		Upduser     string     `json:"updateuser" bson:"updateuser"`   //更新人
		Updtime     time.Time  `json:"updatetime" bson:"updatetime"`   //更新时间
	}
	Material struct {
		OID          	string       `json:"oid" bson:"oid"`
		RelPro         string       `json:"relpro" bson:"relpro"`                                   //关联生产组id
		LargeCargoNumber string  `json:"largecargonumber" bson:"largecargonumber"` //大货号
		ModelName        string  `json:"modelname" bson:"modelname"`               //款式名称
		ProductColor     string  `json:"productcolor" bson:"productcolor"`         //产品颜色
		Name             string  `json:"name" bson:"name"`                         // 物料描述
		ID               string  `json:"id" bson:"id"`                             // 公司编号
		Code             string  `json:"code" bson:"code"`                         // 工厂编号
		Color            string  `json:"color" bson:"color"`                       // 颜色
		Colorcode        string  `json:"colorcode" bson:"colorcode"`               // 工厂色号
		Material         string  `json:"material" bson:"material"`                 // 材质
		Compose          string  `json:"compose" bson:"compose"`                   // 工厂成分
		Menfu            string  `json:"menfu" bson:"menfu"`                       //门幅
		Size             string  `json:"size" bson:"size"`                         // 规格
		Weight           string  `json:"weight" bson:"weight"`                     // 克重
		Shazhi           string  `json:"shazhi" bson:"shazhi"`                     // 纱之
		Cost             string  `json:"cost" bson:"cost"`                         //单价
		Provider         string  `json:"provider" bson:"provider"`                 //供应商
		Type             string  `json:"type" bson:"type"`                         //大类
		Smalltype        string  `json:"smalltype" bson:"smalltype"`               //类目
		Note             string  `json:"note" bson:"note"`                         //备注
		Part             string  `json:"part" bson:"part"`                         //部位
		Expend           string  `json:"expend" bson:"expend"`                     //单耗
		Money            float64 `json:"money" bson:"money"`                       //金额
		Destination      string  `json:"destination" bson:"destination"`           //目的地
		Time             string  `json:"time" bson:"time"`                         //发货时间
		Receive          string  `json:"receive" bson:"receive"`                   //是否到货
		Contractno       string  `json:"contractno" bson:"contractno"`             //合同号
		Ordercount       float64  `json:"ordercount" bson:"ordercount"`             //建议数量
		Actualcount      float64  `json:"actualcount" bson:"actualcount"`             //实际数量
		Actualmoney      float64  `json:"actualmoney" bson:"actualmoney"`             //实际金额
		Brand            string                     `json:"brand" bson:"brand"`                                     //品牌

	}
)

type OXYPurchasesData struct{}

func NewPurchasesData() *OXYPurchasesData {
	Data := &OXYPurchasesData{}
	return Data
}

func (oi *OXYPurchasesData) GetListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Purchases{}
	query.All(&ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  ps,
		"count": count,
	})

	return nil
}

func (oi *OXYPurchasesData) GetInfoHandler(c echo.Context) error {
	log.Info("GetInfoHandler")
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Purchases{}
	query.One(&p)

	List := []bson.M{}
	if len(p.ProductIds) == 0 {
		c.JSON(200, map[string]interface{}{
			"msg":  "success",
			"data": p,
		})
		return nil
	}
	for _, v := range p.ProductIds {
		List = append(List, bson.M{"relpro": v})
	}
	M := bson.M{"$or": List}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan_order"
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	productsquery, _, err := model.DB().QuerySort(M, 0, 0, "_id")
	if err != nil {
		log.Error("查询出错,product_plan_order:", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	productsquery.All(&p.Products)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	MList := []bson.M{}
	if len(p.MaterialIds) == 0 {
		c.JSON(200, map[string]interface{}{
			"msg":  "success",
			"data": p,
		})
		return nil
	}
	for _, v := range p.MaterialIds {
		MList = append(MList, bson.M{"oid": v})
	}
	MM := bson.M{"$or": MList}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_material"
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	materialsquery, _, err := model.DB().Query(MM, 0, 0)
	if err != nil {
		log.Error("查询出错,order_material:", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	materialsquery.All(&p.Materials)
	if err != nil {
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": p,
	})
	return nil
}

func (oi *OXYPurchasesData) AddHandler(c echo.Context) error {
	log.Info("AddHandler")

	p := &InsertPurchases{}
	if err := c.Bind(p); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	var MaterialList []interface{}
	var materialids []string
	for _,v:= range p.Materials{
		v.OID =  xid.New().String()
		MaterialList = append(MaterialList,v)
		materialids = append(materialids,v.OID)
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_material"
	err := model.DB().InsertAll(MaterialList...)
	if err != nil {
		log.Error("插入 order_material 物料信息出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	purchases:=InsertPurchases{
		OrderNumber:p.OrderNumber,
		ProductIds:p.ProductIds,
		MaterialIds:materialids,
		Creuser:p.Creuser,
		Cretime:time.Now(),
		Upduser:p.Upduser,
	}
	err = model.DB().Insert(purchases)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (oi *OXYPurchasesData) UpdateHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateHandler", id)
	p := &InsertPurchases{}
	p.Updtime = time.Now()
	if err := c.Bind(p); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}


	oldP := &InsertPurchases{}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	oldQ,err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	oldQ.One(oldP)
	Dmaterialids := []bson.M{}
	for _,v:= range oldP.MaterialIds{
		Dmaterialids = append(Dmaterialids,bson.M{"oid":v})
	}
	log.Info("Dmaterialids",Dmaterialids)
	MM := bson.M{"$or": Dmaterialids}
	if len(Dmaterialids)>0{
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "order_material"
		_,err = model.DB().RemoveAll(MM)
		if err != nil {
			log.Error("删除原有order_material 物料信息出错", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}
	}
	var MaterialList []interface{}
	var materialids []string
	for _,v:= range p.Materials{
		v.OID =  xid.New().String()
		MaterialList = append(MaterialList,v)
		materialids = append(materialids,v.OID)
	}
	if len(MaterialList)>0{
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "order_material"
		err = model.DB().InsertAll(MaterialList...)
		if err != nil {
			log.Error("插入 order_material 物料信息出错", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}
	}
	p.MaterialIds = materialids
	p.Materials = nil
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	err = model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, p)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
func (oi *OXYPurchasesData) DelHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "purchases"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := Purchases{}
	query.One(&p)

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_material"
	Dmaterialids := []bson.M{}
	for _,v:= range p.MaterialIds{
		Dmaterialids = append(Dmaterialids,bson.M{"oid":v})
	}
	MM := bson.M{"$or": Dmaterialids}
	if len(Dmaterialids)>0{
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "order_material"
		_,err = model.DB().RemoveAll(MM)
		if err != nil {
			log.Error("删除原有order_material 物料信息出错", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}
		}
	List := []bson.M{}
	for _, v := range p.ProductIds {
		List = append(List, bson.M{"relpro": v})
	}
	log.Info("p.ProductIds",p.ProductIds)
	log.Info("List",List)
	M := bson.M{"$or": List}
	model.DB().Document = "product_plan_order"
	_,err = model.DB().UpdateAll(M, bson.M{"$set": bson.M{"purchasesstatus": "0"}})
	
	model.DB().Document = "purchases"
	err = model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func (oi *OXYPurchasesData) GetMaterialListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_material"
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Material{}
	query.All(&ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  ps,
		"count": count,
	})

	return nil
}

func (oi *OXYPurchasesData) GeStatisticsHandler(c echo.Context) error {
	jsonquery := c.QueryParam("like")
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "order_material"
	query, _, err := model.DB().QuerySort(M, 0, 0, "_id")
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []Material{}
	query.All(&ps)

	var  money float64;
	for _,v:= range ps{
		money += v.Actualmoney
	}
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  money,
	})

	return nil
}

